if
and else
¶NOTES
Today we're going to look at some more of the fundamental tools in programming.
if
¶NOTES
red_dots.py
Look at control flow
Comment on event stream pattern: the outer loop moves Bit along towards a goal, while the if
handles events that come up along the way.
%%file red_dots.py
from byubit import Bit
@Bit.run('red-dots')
def go(bit):
while bit.front_clear():
bit.move()
if bit.is_red():
bit.paint('blue')
else
¶NOTES
if
block run? When is the else
block run?%%file more_red_dots.py
from byubit import Bit
@Bit.run('more-red-dots')
def go(bit):
while bit.front_clear():
bit.move()
if bit.is_red():
bit.paint('blue')
else:
bit.paint('green')
elif
¶turns.py
¶NOTES
elif
block checks conditionselse
block doesn't check a condition%%file turns.py
from byubit import Bit
@Bit.run('turns')
def go(bit):
while bit.front_clear():
bit.move()
if bit.is_red():
bit.left()
elif bit.is_green():
bit.right()
else:
bit.paint('blue')
# Solution
from byubit import Bit
@Bit.run('holes')
@Bit.pictures('images/')
def run(bit):
bit.paint('blue')
while bit.front_clear():
bit.move()
if bit.right_clear():
bit.paint('red')
elif bit.left_clear():
bit.paint('green')
else:
bit.paint('blue')
holes.py
¶Bit is in the pipes, and the pipes have holes. Bit's job is to mark where the holes are so someone else can fix them.
NOTES
Draw it out! Give the students time to discuss how they would solve this.
Demonstrate general strategy: how we can use a while
to move Bit to the end goal and use if
to handle events along the way. Event stream pattern
Errors:
elif
(put it outside the if/else
control)Explore:
# Solution
from byubit import Bit
@Bit.run('fly')
@Bit.pictures('images/')
def run(bit):
while not bit.is_red():
if bit.is_blue():
bit.left()
elif bit.is_green():
bit.right()
bit.move()
fly.py
¶Bit is out flying around.
When Bit finds a blue square, he turns left.
When Bit finds a green square, he turns right.
When Bit finds a red square, he stops.
NOTES
Draw it out!
Errors: how do you identify and fix them?
front_clear()
instead of not is_red()
(misses red square)Does it matter if you move-then-turn vs turn-then-move?
NOTES
This activity prepares the students for waterfall.py
in the lab.
while
condition?Now write a single function that can allow Bit to travel in either direction.
NOTES
Add in 'more-elevators'
as a test case. Observe the problem: Bit turns into the floor when heading from left to right.
How do we know which way to turn to rise?
Similar "rise" blocks: each has a while loop, but the turns are different.
Nested: while
if
if
while
if
, else
, and elif
while
with inner if